package com.cn.util;

import com.alibaba.fastjson.JSONObject;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ConnectTimeoutException;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.ssl.SSLContextBuilder;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.util.UriComponentsBuilder;

import javax.net.ssl.SSLContext;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 需要项目初始化
 */
public class HttpsClientUtil {

    private static CloseableHttpClient httpClient;

    private static final Logger logger = LoggerFactory.getLogger(HttpsClientUtil.class);

    static {
        try {
            SSLContext sslContext = SSLContextBuilder.create().useProtocol(SSLConnectionSocketFactory.SSL).loadTrustMaterial((x, y) -> true).build();
            RequestConfig config = RequestConfig.custom().setConnectTimeout(1000).setSocketTimeout(60000).build();
            httpClient = HttpClientBuilder.create().setDefaultRequestConfig(config).setSSLContext(sslContext).setSSLHostnameVerifier((x, y) -> true).build();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
//        try {
//            SSLContext sslContext = SSLContextBuilder.create().useProtocol(SSLConnectionSocketFactory.SSL).loadTrustMaterial((x, y) -> true).build();
//            RequestConfig config = RequestConfig.custom().setConnectTimeout(1000).setSocketTimeout(60000).build();
//            httpClient = HttpClientBuilder.create().setDefaultRequestConfig(config).setSSLContext(sslContext).setSSLHostnameVerifier((x, y) -> true).build();
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
        String url = "https://10.101.50.85:23000/v1/user";
        Map map = new HashMap();
        map.put("access_token","50MVS5ZMbYoHoMqN");
        doPostFrom(url,map);

    }


    public static String doPost1(String url, String jsonString,Integer time) {
        HttpPost httpPost = null;
        try {
            httpPost = new HttpPost(url);
            StringEntity stringEntity = new StringEntity(jsonString, "utf-8");
            stringEntity.setContentType("application/x-www-form-urlencoded");
            httpPost.setEntity(stringEntity);
            Long startTime = System.currentTimeMillis();
            RequestConfig requestConfig = RequestConfig.custom().
                    setConnectTimeout(time).setConnectTimeout(time).setSocketTimeout(time).build();
            httpPost.setConfig(requestConfig);
            CloseableHttpResponse response = httpClient.execute(httpPost);
            int statusCode = response.getStatusLine().getStatusCode();
            if (statusCode != 200) {
                httpPost.abort();
                throw new RuntimeException("HttpClient,error status code :"
                        + statusCode);
            }
            HttpEntity entity = response.getEntity();
            String result = null;
            if (entity != null) {
                result = EntityUtils.toString(entity, "utf-8");
            }
            EntityUtils.consume(entity);
            System.out.println("数据查询耗时："+(System.currentTimeMillis()-startTime)+"ms");
            response.close();
            return result;
        } catch (ConnectTimeoutException e){
            logger.info("连接超时："+e.getMessage());
        } catch (Exception e) {
            logger.error("请求报错：{}", e.getMessage(), e);
        } finally {
            if (httpPost != null) {
                httpPost.releaseConnection();
            }
        }

        return "";
    }

    public static String doPost(String url, String jsonString,Integer time) {
        HttpPost httpPost = null;
        try {
            httpPost = new HttpPost(url);
            StringEntity stringEntity = new StringEntity(jsonString, "utf-8");
            stringEntity.setContentType("application/json");
            httpPost.setEntity(stringEntity);
            Long startTime = System.currentTimeMillis();
            RequestConfig requestConfig = RequestConfig.custom().
                    setConnectTimeout(time).setConnectTimeout(time).setSocketTimeout(time).build();
            httpPost.setConfig(requestConfig);
            CloseableHttpResponse response = httpClient.execute(httpPost);
            int statusCode = response.getStatusLine().getStatusCode();
            if (statusCode != 200) {
                httpPost.abort();
                throw new RuntimeException("HttpClient,error status code :"
                        + statusCode);
            }
            HttpEntity entity = response.getEntity();
            String result = null;
            if (entity != null) {
                result = EntityUtils.toString(entity, "utf-8");
            }
            EntityUtils.consume(entity);
            System.out.println("数据查询耗时："+(System.currentTimeMillis()-startTime)+"ms");
            response.close();
            return result;
        } catch (ConnectTimeoutException e){
            logger.info("连接超时："+e.getMessage());
        } catch (Exception e) {
            logger.error("请求报错：{}", e.getMessage(), e);
        } finally {
            if (httpPost != null) {
                httpPost.releaseConnection();
            }
        }

        return "";
    }

    public static String doPostFrom(String url, Map<String, String> headers) {

        List<NameValuePair> params = new ArrayList<>();
//        CloseableHttpClient client = SSLClient.createSSLClient();
        HttpPost httpPost = new HttpPost(url);
        String msg = "";
        try {
            if (headers != null && headers.size() != 0) {
                for (Map.Entry<String, String> entry : headers.entrySet()) {
                    params.add(new NameValuePair() {
                        @Override
                        public String getName() {
                            return entry.getKey();
                        }

                        @Override
                        public String getValue() {
                            return entry.getValue();
                        }
                    });
                }
            }
            httpPost.setEntity(new UrlEncodedFormEntity(params, StandardCharsets.UTF_8));
            httpPost.setHeader("Content-type", "application/x-www-form-urlencoded");
            HttpResponse response = httpClient.execute(httpPost);
            int statusCode = response.getStatusLine().getStatusCode();
            if (HttpURLConnection.HTTP_OK == statusCode) {
                HttpEntity entity = response.getEntity();
                msg = EntityUtils.toString(entity);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return msg;
    }


    public static String doPost(String url, String jsonString) {
        HttpPost httpPost = null;
        try {
            httpPost = new HttpPost(url);
            StringEntity stringEntity = new StringEntity(jsonString, "utf-8");
            stringEntity.setContentType("application/json");
            httpPost.setEntity(stringEntity);
            CloseableHttpResponse response = httpClient.execute(httpPost);
            int statusCode = response.getStatusLine().getStatusCode();
            if (statusCode != 200) {
                httpPost.abort();
                throw new RuntimeException("HttpClient,error status code :"
                        + statusCode);
            }
            InputStream content = response.getEntity().getContent();
            HttpEntity entity = response.getEntity();
            String result = null;
            if (entity != null) {
                result = EntityUtils.toString(entity, "utf-8");
            }
            EntityUtils.consume(entity);
            response.close();
            return result;
        } catch (ConnectTimeoutException e){
            logger.info("连接超时："+e.getMessage());
        } catch (Exception e) {
            logger.error("请求报错：{}", e.getMessage(), e);
        } finally {
            if (httpPost != null) {
                httpPost.releaseConnection();
            }
        }
        return "";
    }


    public static String doGet(String url) {
        HttpGet httpGet = null;
        try {
            httpGet = new HttpGet(url);
            CloseableHttpResponse response = httpClient.execute(httpGet);
            int statusCode = response.getStatusLine().getStatusCode();
            if (statusCode != 200) {
                httpGet.abort();
                throw new RuntimeException("HttpClient,error status code :"
                        + statusCode);
            }
            HttpEntity entity = response.getEntity();
            String result = null;
            if (entity != null) {
                result = EntityUtils.toString(entity, "utf-8");
            }
            EntityUtils.consume(entity);
            response.close();
            return result;
        } catch (ConnectTimeoutException e){
            logger.info("连接超时："+e.getMessage());
        } catch (Exception e) {
            logger.error("请求报错：{}", e.getMessage(), e);
        } finally {
            if (httpGet != null) {
                httpGet.releaseConnection();
            }
        }
        return "";
    }

    public static String doGet(String url, Map paramMap) {
        HttpGet httpGet = null;
        try {
            UriComponentsBuilder build = UriComponentsBuilder.fromHttpUrl(url);
            paramMap.forEach((k,v)->build.queryParam((String) k,v));

            httpGet = new HttpGet(build.build().toUri());
            CloseableHttpResponse response = httpClient.execute(httpGet);
            int statusCode = response.getStatusLine().getStatusCode();
            if (statusCode != 200) {
                httpGet.abort();
                throw new RuntimeException("HttpClient,error status code :"
                        + statusCode);
            }
            HttpEntity entity = response.getEntity();
            String result = null;
            if (entity != null) {
                result = EntityUtils.toString(entity, "utf-8");
            }
            EntityUtils.consume(entity);
            response.close();
            return result;
        } catch (ConnectTimeoutException e){
            logger.info("连接超时："+e.getMessage());
        } catch (Exception e) {
            logger.error("请求报错：{}", e.getMessage(), e);
        } finally {
            if (httpGet != null) {
                httpGet.releaseConnection();
            }
        }
        return "";
    }

}

